
package org.open.sharedRadar;

import org.ksoap2.serialization.SoapObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase.CursorFactory;



public class DBAdapter {
	public static final String DB_NAME = "SharedRadarDB";
	public static final String DB_TABLEUL = "UltimaLocatie";
	public static final String DB_TABLEFR = "FriendsRadarsLoc";
	public static final String DB_USERTBL = "UserPreferences";
	public static final String DB_FRIENDS = "FriendsRequests";
	
	public static final int DB_VERSION = 1;
	private final Context context;
	private SQLiteDatabase myDB;
	private DatabaseHelper myDBHelper;
	
	public DBAdapter(Context context) {
		this.context = context;
	}
	public DBAdapter open() throws SQLException {
		this.myDBHelper = new DatabaseHelper (this.context, DB_NAME,  null, DB_VERSION);
		this.myDB = this.myDBHelper.getWritableDatabase();	
		return this;	
	}
	
	public boolean isOpen(){
		return myDB != null && myDB.isOpen();
	}
	
	public void close() {
		if (isOpen()) 
		{
			this.myDB.close();
			this.myDB = null;
			if (this.myDBHelper != null)
			{
				this.myDBHelper.close();
				this.myDBHelper = null;				
			}			
		}	
	}
	private static class DatabaseHelper extends SQLiteOpenHelper{
		private static final String CREATE_TABLE_ULTIMALOCATIE = " create table "
				+ DBAdapter.DB_TABLEUL
				+ " (_id integer primary key autoincrement, " + "pozLong text, " 
				+ "pozLat text, " + "observatie text, " +"data text);";
		private static final String CREATE_TABLE_LOCATIIFR = " create table "
				+ DBAdapter.DB_TABLEFR
				+ " (_id integer primary key autoincrement, " + "displayName text, " + "pozLong text, " 
				+ "pozLat text, " + "tipLocatie text);";
		private static final String CREATE_TABLE_DB_USERTBL = " create table "
				+ DBAdapter.DB_USERTBL
				+ " (_id integer primary key autoincrement, " + "userName text, " + "parola text, " + "pozLong text, " 
				+ "pozLat text, " +  "refreshInterval text, " +"raza text);";
		private static final String CREATE_TABLE_DB_FRIENDS = " create table "
				+ DBAdapter.DB_FRIENDS
				+ " (_id integer primary key autoincrement, " + "userName text, " + "status text);";
		
		public DatabaseHelper(Context context, String name, CursorFactory factory, int version){
			super(context, DBAdapter.DB_NAME, null, DBAdapter.DB_VERSION);
		}
		
		
		public void onCreate(SQLiteDatabase db){
			db.execSQL(CREATE_TABLE_ULTIMALOCATIE);
			db.execSQL(CREATE_TABLE_LOCATIIFR);
			db.execSQL(CREATE_TABLE_DB_USERTBL);
			db.execSQL(CREATE_TABLE_DB_FRIENDS);
		}
		
		
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
			db.execSQL("DROP TABLE IF EXISTS" + DBAdapter.DB_TABLEUL);
			db.execSQL("DROP TABLE IF EXISTS" + DBAdapter.DB_TABLEFR);
			db.execSQL("DROP TABLE IF EXISTS" + DBAdapter.DB_USERTBL);
			db.execSQL("DROP TABLE IF EXISTS" + DBAdapter.DB_FRIENDS);
			
			onCreate(db);
		}		
	}		
	
	public void parseUserDataToFromDB(Boolean to_){						
		try
		{																		
			if(to_)
			{
				ContentValues cv = new ContentValues();
				if(CurentUserProperties.getInstance().currentUserId == null || CurentUserProperties.getInstance().currentPass == null)
					return;
				this.myDB.delete("UserPreferences", null, null);
				String toParse = "";
				String toParseInterval = "";
				toParse = CurentUserProperties.getInstance().currentUserId;
				cv.put("userName", toParse);
				toParse = CurentUserProperties.getInstance().currentPass;
				cv.put("parola", toParse);				
				toParseInterval = CurentUserProperties.getInstance().myInterval.toString();
				cv.put("refreshInterval", toParseInterval);
				toParse = CurentUserProperties.getInstance().myRadius.toString();
				cv.put("raza", toParse);
				this.myDB.insert("UserPreferences", null, cv);
				if(CurentUserProperties.getInstance().currentUserId != null && CurentUserProperties.getInstance().myCurrentLocation != null)
				{
					WebServiceHandler handler = new WebServiceHandler();
					handler.updateLocation();
				}
			}
			else
			{				
				Cursor cursor =  this.myDB.query(DBAdapter.DB_USERTBL, new String[] {"userName","parola","pozLong", "pozLat", "refreshInterval", "raza"},null,null,null,null,null);						  	    	  
				cursor.moveToFirst();
				while (cursor.isAfterLast() == false) 
				{
					CurentUserProperties.getInstance().currentUserId = cursor.getString(0);
					CurentUserProperties.getInstance().currentPass = cursor.getString(1);
					String interval = cursor.getString(4);
					String radius = cursor.getString(5);
					if(interval != null)
						CurentUserProperties.getInstance().myInterval = Integer.parseInt(interval);
					else
						CurentUserProperties.getInstance().myInterval = 1;
					
					if(radius != null)
						CurentUserProperties.getInstance().myRadius = Integer.parseInt(radius);
					else										
						CurentUserProperties.getInstance().myRadius = 10000;
					cursor.moveToNext();
				}				
			    cursor.close();			    
			}
		}
		catch (Exception aE)
	    {
	       aE.printStackTrace ();	       
	    }			  	  					
	}	
	
	public Cursor getAllLocatii(){
		return this.myDB.query(DBAdapter.DB_TABLEUL, new String[] 
				{"_id", "pozLong", "pozLat", "observatie", "data"}, null, null, null, null, null);
	}
	
	public void salveazaLocatieCurenta(Locatie locatie){
		this.myDB.delete("UltimaLocatie", null, null);
		ContentValues cv = new ContentValues();
		cv.put("pozLong", locatie.getPozLong());
		cv.put("pozLat", locatie.getPozLat());
		cv.put("observatie", locatie.getObservatie());
		cv.put("data", locatie.getData());
		this.myDB.insert("UltimaLocatie", null, cv);
	}	
	
	public Cursor getLocationsFromDB(Boolean radars_){		
		Cursor result = null;
		try
		{			
			String tipLocatie = "";
			if(radars_)
				tipLocatie = "Radar";
			else
				tipLocatie = "Prieten";			
			String where = "tipLocatie = '" + tipLocatie + "'";			
			result =  this.myDB.query(DBAdapter.DB_TABLEFR, new String[] {"displayName", "pozLong", "pozLat"},where,null,null,null,null);
			return result;
								
		}
		catch (Exception aE)
	    {
	       aE.printStackTrace ();	       
	    }
		return result;
  	  						
	}	
	
	public void synchronizeLocationsWithWeb(){		
		
		try
		{			
			WebServiceHandler handler = new WebServiceHandler();
			SoapObject listaObiecte = null;				
			listaObiecte = handler.getRadars();  	 		
			this.myDB.delete("FriendsRadarsLoc", null, null);
			for(int i= 0; i < listaObiecte.getPropertyCount(); i++)
			{	
				SoapObject soapRadar = (SoapObject) listaObiecte.getProperty(i);	    		  
	    	   	 						   
				ContentValues cv = new ContentValues();
				cv.put("displayName", soapRadar.getProperty(0).toString());
				cv.put("pozLong", soapRadar.getProperty(1).toString());
				cv.put("pozLat", soapRadar.getProperty(2).toString());			
				cv.put("tipLocatie", "Radar");
				this.myDB.insert("FriendsRadarsLoc", null, cv);
			}		
			
			listaObiecte = handler.getFriends();
			for(int i= 0; i < listaObiecte.getPropertyCount(); i++)
			{	
				SoapObject soapFriend = (SoapObject) listaObiecte.getProperty(i);	    		  
	    	   	 						   
				ContentValues cv = new ContentValues();
				cv.put("displayName", soapFriend.getProperty(0).toString());
				cv.put("pozLong", soapFriend.getProperty(1).toString());
				cv.put("pozLat", soapFriend.getProperty(2).toString());			
				cv.put("tipLocatie", "Prieten");
				this.myDB.insert("FriendsRadarsLoc", null, cv);
			}	
		}
		catch (Exception aE)
	    {
	       aE.printStackTrace ();	       
	    }
  	  						
	}	
	
	public void synchronizeFriendsReqWithWeb(){		
		
		try
		{			
			WebServiceHandler handler = new WebServiceHandler();
			SoapObject listaObiecte = null;				
			listaObiecte = handler.getFriendsRequests();  	 		
			this.myDB.delete("FriendsRequests", null, null);
			for(int i= 0; i < listaObiecte.getPropertyCount(); i++)
			{	
				SoapObject soapFriendReq = (SoapObject) listaObiecte.getProperty(i);	    		  
	    	   	 						   
				ContentValues cv = new ContentValues();
				cv.put("userName", soapFriendReq.getProperty(0).toString());
				
				String status = soapFriendReq.getProperty(1).toString();
				char sts = status.charAt(0);
				if(sts == 'N')
					status = "Neconfirmat";
				else
					status = "Confirmat";
					
				cv.put("status", status);				
				this.myDB.insert("FriendsRequests", null, cv);
			}								
		}
		catch (Exception aE)
	    {
	       aE.printStackTrace ();	       
	    }
  	  						
	}	
	public void updateDeleteFriend(String userName_, boolean update_)
	{		
		try
		{									
			String where = " WHERE userName = '" + userName_ + "';";
			String sqlString = "";
			if(update_)
				sqlString = "UPDATE " + DBAdapter.DB_FRIENDS + " SET status = 'Confirmat' " + where;
			else
				sqlString = "DELETE FROM " + DBAdapter.DB_FRIENDS + where;
			this.myDB.execSQL(sqlString);										
		}
		catch (Exception aE)
	    {
	       aE.printStackTrace ();	       
	    }		
	}
	
	public Cursor getFriendsRequests()
	{
		Cursor result = null;
		try
		{									
			result =  this.myDB.query(DBAdapter.DB_FRIENDS, new String[] {"_id", "userName", "status"},null,null,null,null,null);
			return result;
								
		}
		catch (Exception aE)
	    {
	       aE.printStackTrace ();	       
	    }
		return result;
	}
}


